package com.runewbie.pafcmall.ware.service.impl;

import com.runewbie.common.constant.WareConstant;
import com.runewbie.pafcmall.ware.entity.PurchaseDetailEntity;
import com.runewbie.pafcmall.ware.service.PurchaseDetailService;
import com.runewbie.pafcmall.ware.service.WareSkuService;
import com.runewbie.pafcmall.ware.vo.MergePurchaseVo;
import com.runewbie.pafcmall.ware.vo.PurchaseDoneVo;
import com.runewbie.pafcmall.ware.vo.PurchaseItemDoneVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.runewbie.common.utils.PageUtils;
import com.runewbie.common.utils.Query;

import com.runewbie.pafcmall.ware.dao.PurchaseDao;
import com.runewbie.pafcmall.ware.entity.PurchaseEntity;
import com.runewbie.pafcmall.ware.service.PurchaseService;
import org.springframework.transaction.annotation.Transactional;


@Service("purchaseService")
public class PurchaseServiceImpl extends ServiceImpl<PurchaseDao, PurchaseEntity> implements PurchaseService {

    @Autowired
    PurchaseDetailService purchaseDetailService;
    @Autowired
    WareSkuService wareSkuService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<PurchaseEntity> page = this.page(
                new Query<PurchaseEntity>().getPage(params),
                new QueryWrapper<PurchaseEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public PageUtils queryPageUnreceivedPurchase(Map<String, Object> params) {
        QueryWrapper<PurchaseEntity> wrapper = new QueryWrapper<>();
        wrapper.eq("status", WareConstant.PurchaseDetailStatusEnum.CREATED.getCode())
                .or().eq("status", WareConstant.PurchaseDetailStatusEnum.ASSIGNED.getCode());

        IPage<PurchaseEntity> page = this.page(
                new Query<PurchaseEntity>().getPage(params),
                wrapper
        );

        return new PageUtils(page);

    }

    @Transactional // 开启事务
    @Override
    public void mergePurchase(MergePurchaseVo mergePurchaseVo) {
        // 确认采购项状态是0,1才可以合并
        List<Long> items = mergePurchaseVo.getItems();
        items = items.stream().map(id -> {
            // 先根据id获取采购详情信息
            PurchaseDetailEntity detailEntity = purchaseDetailService.getById(id);
            return detailEntity;
        }).filter(detailEntity -> {
            // 过滤出新建的和已分配的采购单
            if (detailEntity.getStatus() == WareConstant.PurchaseDetailStatusEnum.CREATED.getCode()
                    || detailEntity.getStatus() == WareConstant.PurchaseDetailStatusEnum.ASSIGNED.getCode()) {
                return true;
            }
            return false;
        }).map(detailEntity -> {
            // 返回符合条件的采购单id
            return detailEntity.getId();
        }).collect(Collectors.toList());

        if (items == null || items.size() == 0) {
            return;
        }

        // 如果没有采购单，就新建一个采购单，将采购需求合并到新的采购单；否则就合并到指定的采购单
        Long purchaseId = mergePurchaseVo.getPurchaseId();
        if (purchaseId == null) {
            // 新建采购单
            PurchaseEntity purchase = new PurchaseEntity();
            purchase.setStatus(WareConstant.PurchaseStatusEnum.CREATED.getCode());
            purchase.setCreateTime(new Date());
            purchase.setUpdateTime(new Date());
            this.save(purchase);

            purchaseId = purchase.getId();
        }

        Long finalPurchaseId = purchaseId;
        // 批量跟新采购需求表
        List<PurchaseDetailEntity> purchaseDetailEntities = items.stream().map(i -> {
            PurchaseDetailEntity purchaseDetail = new PurchaseDetailEntity();
            purchaseDetail.setId(i);
            purchaseDetail.setPurchaseId(finalPurchaseId);
            purchaseDetail.setStatus(WareConstant.PurchaseDetailStatusEnum.ASSIGNED.getCode());

            return purchaseDetail;
        }).collect(Collectors.toList());

        purchaseDetailService.updateBatchById(purchaseDetailEntities);

        // 最后还需要更新一下采购单的时间
        PurchaseEntity purchaseEntity = new PurchaseEntity();
        purchaseEntity.setId(finalPurchaseId);
        purchaseEntity.setUpdateTime(new Date());
        this.updateById(purchaseEntity);
    }

    @Transactional // 开启事务
    @Override
    public void received(List<Long> ids) {
        // 1、确认当前采购单是新建或者已分配状态
        List<PurchaseEntity> purchaseEntities = ids.stream().map(id -> {
            // 根据id查询采购单
            PurchaseEntity entity = this.getById(id);
            return entity;
        }).filter(item -> {
            // 筛选出新建和已分配的采购单
            if (item.getStatus() == WareConstant.PurchaseStatusEnum.CREATED.getCode()
                    || item.getStatus() == WareConstant.PurchaseStatusEnum.ASSIGNED.getCode()) {
                return true;
            }
            return false;
        }).map(item -> {
            // 改变采购单的状态为已领取
            item.setStatus(WareConstant.PurchaseStatusEnum.RECEIVE.getCode());
            item.setUpdateTime(new Date());
            return item;
        }).collect(Collectors.toList());

        // 2、改变采购单的状态
        this.updateBatchById(purchaseEntities);

        // 3、改变采购项的状态
        purchaseEntities.forEach((item) -> {
            // 根据purchaseId查找采购信息详情列表信息
            List<PurchaseDetailEntity> purchaseDetailEntities = purchaseDetailService.listDetailByPurchaseId(item.getId());

            // 改变采购项的状态
            List<PurchaseDetailEntity> detailEntityList = purchaseDetailEntities.stream().map(detailEntity -> {
                PurchaseDetailEntity entity = new PurchaseDetailEntity();
                entity.setId(detailEntity.getId());
                entity.setStatus(WareConstant.PurchaseDetailStatusEnum.PROCURING.getCode());

                return entity;
            }).collect(Collectors.toList());

            // 更新采购项
            purchaseDetailService.updateBatchById(detailEntityList);
        });
    }

    @Transactional // 添加事务
    @Override
    public void done(PurchaseDoneVo doneVo) {
        // 1、改变采购项的状态
        Boolean flag = true;
        List<PurchaseItemDoneVo> items = doneVo.getItems();

        List<PurchaseDetailEntity> updates = new ArrayList<>();
        for (PurchaseItemDoneVo item : items) {
            PurchaseDetailEntity detailEntity = new PurchaseDetailEntity();
            if (item.getStatus() == WareConstant.PurchaseDetailStatusEnum.FAILED.getCode()) {
                flag = false;
                detailEntity.setStatus(item.getStatus());
            } else {
                detailEntity.setStatus(WareConstant.PurchaseDetailStatusEnum.FINISH.getCode());
                // 将成功采购的进行入库
                PurchaseDetailEntity detail = purchaseDetailService.getById(item.getItemId());
                wareSkuService.addStock(detail.getSkuId(),detail.getWareId(),detail.getSkuNum());
            }
            detailEntity.setId(item.getItemId());
            updates.add(detailEntity);
        }

        purchaseDetailService.updateBatchById(updates);

        // 2、改变采购单的状态
        PurchaseEntity purchaseEntity = new PurchaseEntity();
        purchaseEntity.setId(doneVo.getId());
        purchaseEntity.setStatus(flag ?
                WareConstant.PurchaseStatusEnum.FINISH.getCode() : WareConstant.PurchaseStatusEnum.HAS_ERROR.getCode());
        this.updateById(purchaseEntity);

    }

}